"""
初始化数据脚本
- 创建预设角色：超级管理员、普通员工、客服
- 创建预设资源/菜单
- 创建超级管理员账号
"""
import asyncio
from tortoise import Tortoise
from models.m import Role, Resource, AdminUser
from utils.password_utils import hash_password
from config.config import TORTOISE_ORM


async def init_roles():
    """初始化角色"""
    print("🔧 初始化角色...")
    
    roles_data = [
        {
            "name": "超级管理员",
            "code": "super_admin",
            "description": "拥有系统所有权限",
            "status": 1
        },
        {
            "name": "普通员工",
            "code": "staff",
            "description": "普通员工角色，可查看业务数据",
            "status": 1
        },
        {
            "name": "客服",
            "code": "customer_service",
            "description": "客服角色，处理用户问题",
            "status": 1
        }
    ]
    
    for role_data in roles_data:
        # 检查是否已存在
        existing = await Role.get_or_none(code=role_data["code"])
        if existing:
            print(f"  ⚠️  角色 {role_data['name']} 已存在，跳过")
            continue
        
        role = await Role.create(**role_data)
        print(f"  ✅ 创建角色: {role.name}")


async def init_resources():
    """初始化资源/菜单"""
    print("\n🔧 初始化资源...")
    
    resources_data = [
        # 一级菜单
        {"name": "首页", "code": "dashboard", "type": 1, "path": "/dashboard", "icon": "HomeFilled", "sort": 1, "pid": None},
        {"name": "系统管理", "code": "system", "type": 1, "path": "/system", "icon": "Setting", "sort": 2, "pid": None},
        {"name": "业务管理", "code": "business", "type": 1, "path": "/business", "icon": "Operation", "sort": 3, "pid": None},
        {"name": "操作日志", "code": "log:view", "type": 1, "path": "/logs", "icon": "Document", "sort": 4, "pid": None},
        {"name": "客服管理", "code": "customer_service:view", "type": 1, "path": "/customer-service", "icon": "ChatDotRound", "sort": 5, "pid": None},
        
        # 系统管理子菜单
        {"name": "管理员管理", "code": "admin_user:view", "type": 1, "path": "/users", "icon": "User", "sort": 1, "pid_code": "system"},
        {"name": "角色管理", "code": "role:view", "type": 1, "path": "/roles", "icon": "UserFilled", "sort": 2, "pid_code": "system"},
        {"name": "资源管理", "code": "resource:view", "type": 1, "path": "/resources", "icon": "Menu", "sort": 3, "pid_code": "system"},
        
        # 业务管理子菜单
        {"name": "用户端用户", "code": "business:user:view", "type": 1, "path": "/business/users", "icon": "Avatar", "sort": 1, "pid_code": "business"},
        {"name": "实名认证", "code": "business:verification:view", "type": 1, "path": "/business/verifications", "icon": "Postcard", "sort": 2, "pid_code": "business"},
        {"name": "训练记录", "code": "business:training:view", "type": 1, "path": "/business/training", "icon": "DataLine", "sort": 3, "pid_code": "business"},
        
        # 按钮权限
        {"name": "新增", "code": "admin_user:create", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "admin_user:view"},
        {"name": "编辑", "code": "admin_user:update", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "admin_user:view"},
        {"name": "删除", "code": "admin_user:delete", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "admin_user:view"},
        {"name": "重置密码", "code": "admin_user:reset_pwd", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "admin_user:view"},
        
        {"name": "新增", "code": "role:create", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "role:view"},
        {"name": "编辑", "code": "role:update", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "role:view"},
        {"name": "删除", "code": "role:delete", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "role:view"},
        {"name": "分配权限", "code": "role:assign_resources", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "role:view"},
        
        {"name": "新增", "code": "resource:create", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "resource:view"},
        {"name": "编辑", "code": "resource:update", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "resource:view"},
        {"name": "删除", "code": "resource:delete", "type": 2, "path": None, "icon": None, "sort": 0, "pid_code": "resource:view"},
    ]
    
    # 先创建所有一级资源
    resource_map = {}
    for res_data in resources_data:
        if res_data.get("pid") is None and "pid_code" not in res_data:
            existing = await Resource.get_or_none(code=res_data["code"])
            if existing:
                resource_map[res_data["code"]] = existing
                print(f"  ⚠️  资源 {res_data['name']} 已存在")
                continue
            
            resource = await Resource.create(
                name=res_data["name"],
                code=res_data["code"],
                type=res_data["type"],
                path=res_data.get("path"),
                icon=res_data.get("icon"),
                sort=res_data["sort"],
                status=1,
                pid_id=None
            )
            resource_map[res_data["code"]] = resource
            print(f"  ✅ 创建资源: {resource.name}")
    
    # 再创建子资源
    for res_data in resources_data:
        if "pid_code" in res_data:
            existing = await Resource.get_or_none(code=res_data["code"])
            if existing:
                print(f"  ⚠️  资源 {res_data['name']} 已存在")
                continue
            
            parent = resource_map.get(res_data["pid_code"])
            if not parent:
                print(f"  ⚠️  父资源 {res_data['pid_code']} 不存在，跳过")
                continue
            
            resource = await Resource.create(
                name=res_data["name"],
                code=res_data["code"],
                type=res_data["type"],
                path=res_data.get("path"),
                icon=res_data.get("icon"),
                sort=res_data["sort"],
                status=1,
                pid_id=parent.id
            )
            resource_map[res_data["code"]] = resource
            print(f"  ✅ 创建资源: {resource.name} (父: {parent.name})")


async def init_admin_user():
    """初始化超级管理员账号"""
    print("\n🔧 初始化超级管理员...")
    
    # 获取超级管理员角色
    super_admin_role = await Role.get_or_none(code="super_admin")
    if not super_admin_role:
        print("  ❌ 超级管理员角色不存在，请先初始化角色")
        return
    
    # 检查是否已有管理员
    existing = await AdminUser.get_or_none(username="admin")
    if existing:
        print("  ⚠️  管理员 admin 已存在")
    else:
        # 创建管理员
        admin = await AdminUser.create(
            username="admin",
            password=hash_password("admin123"),
            real_name="超级管理员",
            email="admin@example.com",
            phone="13800138000",
            status=1,
            role_id=super_admin_role.id
        )
        
        print(f"  ✅ 创建管理员: {admin.username}")
        print(f"  📝 账号: admin")
        print(f"  📝 密码: admin123")


async def init_customer_service_user():
    """初始化客服账号"""
    print("\n🔧 初始化客服账号...")
    
    # 获取客服角色
    customer_service_role = await Role.get_or_none(code="customer_service")
    if not customer_service_role:
        print("  ❌ 客服角色不存在，请先初始化角色")
        return
    
    # 检查是否已有客服账号
    existing = await AdminUser.get_or_none(username="zhang")
    if existing:
        print("  ⚠️  客服账号 zhang 已存在")
        return
    
    # 创建客服账号
    customer_service = await AdminUser.create(
        username="zhang",
        password=hash_password("123123"),
        real_name="客服张三",
        email="zhang@example.com",
        phone="13900139000",
        status=1,
        role_id=customer_service_role.id
    )
    
    print(f"  ✅ 创建客服账号: {customer_service.username}")
    print(f"  📝 账号: zhang")
    print(f"  📝 密码: 123123")


async def assign_resources_to_roles():
    """为角色分配资源权限"""
    print("\n🔧 分配角色权限...")
    
    # 超级管理员拥有所有权限
    super_admin = await Role.get_or_none(code="super_admin")
    if super_admin:
        all_resources = await Resource.all()
        await super_admin.resources.clear()
        await super_admin.resources.add(*all_resources)
        print(f"  ✅ 超级管理员分配 {len(all_resources)} 个权限")
    
    # 普通员工：只能查看业务数据
    staff = await Role.get_or_none(code="staff")
    if staff:
        staff_resources = await Resource.filter(
            code__in=["dashboard", "business", "business:user:view", "business:verification:view", "business:training:view"]
        )
        await staff.resources.clear()
        await staff.resources.add(*staff_resources)
        print(f"  ✅ 普通员工分配 {len(staff_resources)} 个权限")
    
    # 客服：查看业务数据 + 查看日志 + 客服管理
    customer_service = await Role.get_or_none(code="customer_service")
    if customer_service:
        cs_resources = await Resource.filter(
            code__in=["dashboard", "business", "business:user:view", "business:verification:view", "business:training:view", "log:view", "customer_service:view"]
        )
        await customer_service.resources.clear()
        await customer_service.resources.add(*cs_resources)
        print(f"  ✅ 客服分配 {len(cs_resources)} 个权限")


async def main():
    """主函数"""
    print("=" * 50)
    print("开始初始化数据...")
    print("=" * 50)
    
    # 初始化数据库连接
    await Tortoise.init(config=TORTOISE_ORM)
    await Tortoise.generate_schemas()
    
    try:
        # 依次执行初始化
        await init_roles()
        await init_resources()
        await init_admin_user()
        await init_customer_service_user()
        await assign_resources_to_roles()
        
        print("\n" + "=" * 50)
        print("✅ 数据初始化完成！")
        print("=" * 50)
        print("\n📝 默认账号:")
        print("   超级管理员:")
        print("     用户名: admin")
        print("     密码: admin123")
        print("   客服账号:")
        print("     用户名: zhang")
        print("     密码: 123123")
        print("\n🚀 启动命令: python main.py")
        print("📖 API文档: http://127.0.0.1:8001/docs")
        print("=" * 50)
    
    finally:
        await Tortoise.close_connections()


if __name__ == "__main__":
    asyncio.run(main())

